package com.company.Nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * 网络客户端程序
 */
public class NioClient {
    public static void main(String[] args) throws Exception {
        //1.通道
        SocketChannel channel = SocketChannel.open();
        //2.设置阻塞
        channel.configureBlocking(false);//非阻塞
        //3.提供服务器端的ip地址和端口号
        InetSocketAddress address = new InetSocketAddress("127.0.0.1", 9999);
        //4.连接服务器端
        if (!channel.connect(address)) {
            while (!channel.finishConnect()) { //nio作为非阻塞的优势
                System.out.println("Client连接服务器端的同时可以干别的事情");
            }
        }

        //5.找到缓冲区并存入数据
        String msg = "hello server";
        ByteBuffer writeBuffer = ByteBuffer.wrap(msg.getBytes());//使用wrap初始化缓冲区

        //6.发送数据
        channel.write(writeBuffer);

        //阻止程序结束
        System.in.read();

    }

}
